package com.hotel.filtro;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter(filterName = "LoginFiltro")
public class LoginFiltro implements Filter {

	public LoginFiltro() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		try {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse resp = (HttpServletResponse) response;
			HttpSession session = req.getSession(true);
			String url = req.getRequestURL().toString();
			
			if (session.getAttribute("usuariologado") == null && precisaAutenticar(url)) {
				resp.sendRedirect("/Hotel/login.jsf");
			} else {
				chain.doFilter(req, resp);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	boolean precisaAutenticar(String url){
		return !url.contains("login.jsf") && !url.endsWith(".css") && !url.endsWith(".js") && !url.endsWith(".jpg")  
	            && !url.endsWith(".gif") && !url.contains("primefaces.org") && !url.contains("javax.faces.resource");
    }

	public void destroy() {
	}

	public void init(FilterConfig filterConfig) {
	}
}